package com.etc.week7_day04_security.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class SecurityConfig  extends  WebSecurityConfigurerAdapter{
    //这里的 configure(AuthenticationManagerBuilder auth) 需要注入UserDetailsService对象

    @Autowired
    private  UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder getPassWordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //public <T extends UserDetailsService> DaoAuthenticationConfigurer<AuthenticationManagerBuilder, T> userDetailsService(T userDetailsService)
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //1 设置登录有关的参数
        http.formLogin().loginProcessingUrl("/login")
                .defaultSuccessUrl("/index");

        //2 设置访问权限(哪些请求需要登录后才能访问，哪些请求可以允许任何人访问)
        http.authorizeRequests()
                //不需要登录就可以访问
                .antMatchers("login.html","login").permitAll()
                // url + role 角色(权限) 控制方式
                .antMatchers("/patient/**").hasRole("admin")
                .antMatchers("/manager/**").hasRole("manager")
                .antMatchers("/doctor/**").hasRole("doctor")
                //任何都要进行访问权限控制
                .anyRequest()
                .authenticated();
        //3. 禁用csrf防护
        http.csrf().disable();
    }

    /**
     * 继承关系
     * @return
     */
    @Bean
    RoleHierarchy roleHierarchy() {
        RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
        //设置admin角色拥有doctor角色的访问权限
        //设置admin角色拥有manager角色的访问权限
        hierarchy.setHierarchy("ROLE_admin > ROLE_doctor \n ROLE_admin > ROLE_manager");
        return hierarchy;
    }
}
